// 所有的数据操作都由 Redux Toolkit 来完成
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { productsAPI } from "../../api"

// 异步获取全部商品

export const fetchProducts = createAsyncThunk(
    'products/fetchProducts',
    async () => {
        const response = await productsAPI.getAll()
        // 返回的数据会作为 action.payload
        return response.data
    },
)

// 异步获取秒杀商品
export const fetchSeckillProducts = createAsyncThunk(
    'products/fetchSeckillProducts',
    async () => {
        const response = await productsAPI.getSeckill()
        // 返回的数据会作为 action.payload
        return response.data
    },
)

// 异步获取团购商品
export const fetchGroupBuyProducts = createAsyncThunk(
    'products/fetchGroupBuyProducts',
    async () => {
        const response = await productsAPI.getGroupBuy()
        // 返回的数据会作为 action.payload
        return response.data
    },
)

// 定义初始状态
const initialState = {
    allProducts: [],
    // 秒杀商品
    seckillProducts: [],
    // 团购商品
    groupBuyProducts: [],
    // 错误信息
    error: null,
    // 加载状态（有异步） 不需要设置，因为使用的是 createAsyncThunk 的 pending, fulfilled, rejected
    loading: false,

    seckillLoading: false,
    groupBuyLoading: false,

    seckillError: null,
    groupBuyError: null,
}

// 生成 product的 reducer 和 actions
const productsSlice = createSlice({
    name: "products",
    initialState,
    reducers: {},
    // 异步的 处理逻辑
    extraReducers: (builder) => {
        builder
            .addCase(fetchProducts.pending, (state) => {
                state.loading = true
            })
            .addCase(fetchProducts.fulfilled, (state, action) => {
                state.loading = false
                state.allProducts = action.payload
            })
            .addCase(fetchProducts.rejected, (state, action) => {
                state.loading = false
                state.error = action.error.message
            })
            .addCase(fetchSeckillProducts.pending, (state) => {
                state.seckillLoading = true
            })
            .addCase(fetchSeckillProducts.fulfilled, (state, action) => {
                state.seckillLoading = false
                state.seckillProducts = action.payload
            })
            .addCase(fetchSeckillProducts.rejected, (state, action) => {
                state.seckillLoading = false
                state.seckillError = action.error.message
            })
            .addCase(fetchGroupBuyProducts.pending, (state) => {
                state.groupBuyLoading = true
            })
            .addCase(fetchGroupBuyProducts.fulfilled, (state, action) => {
                state.groupBuyLoading = false
                state.groupBuyProducts = action.payload
            })
            .addCase(fetchGroupBuyProducts.rejected, (state, action) => {
                state.groupBuyLoading = false
                state.groupBuyError = action.error.message
            })
    }

})

export default productsSlice.reducer